package com.xdja;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.*;

/**
 * description
 *
 * @author zk
 * @since 2018/9/26
 */
public class LocalHttpProxyStart {
    public static void main(String[] args) throws InterruptedException {
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(new NioEventLoopGroup(),new NioEventLoopGroup())
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ch.pipeline().addLast(new HttpServerCodec()).addLast(new SimpleChannelInboundHandler<HttpObject>() {
                            @Override
                            protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
                                System.out.println();
                                System.out.println("--------------------");

                                if(msg instanceof HttpRequest){
                                    if(((HttpRequest) msg).method() == HttpMethod.CONNECT){
                                        ctx.channel().writeAndFlush(ctx.alloc().buffer().writeBytes(new byte[]{72,84,84,80,47,49,46,49,32,50,48,48,32,79,75,13,10,13,10}));
                                    } else {
//                                        System.out.println("-------------------->" + ctx.channel().id() + " " + msg);
                                    }
                                } else if(msg instanceof HttpContent){
//                                    System.out.println("-------------------->" + ctx.channel().id() + " " + msg);
                                }
                                System.out.println(ctx.channel().id());
                                System.out.println(msg);

                                System.out.println("--------------------");
                            }
                        });
                    }
                });
        ChannelFuture channelFuture = serverBootstrap.bind(8989);
        channelFuture.channel().closeFuture().sync();
    }
}
